package com.lam.datasave.diary;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.lam.fundamental.R;

public class DiaryEditActivity extends Activity{

	private DiaryDBAdapter dbAdapter;
	private Button bt_submit;
	private EditText et_title;
	private EditText et_content;
	private Long rowId;
	private Bundle extBundle;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		dbAdapter=new DiaryDBAdapter(this);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ds_diary_edit);
		
		et_content=(EditText)findViewById(R.id.et_diaryeditContent);
		et_title=(EditText)findViewById(R.id.et_diaryeditTitle);
		
		bt_submit=(Button) findViewById(R.id.bt_diaryeidtSub);
		
		 extBundle=getIntent().getExtras();
		if(extBundle!=null){
			rowId=extBundle.getLong(DiaryDBAdapter.KEY_ROWID);
			String title=extBundle.getString(DiaryDBAdapter.KEY_TITLE);
			String content=extBundle.getString(DiaryDBAdapter.KEY_CONTENT);
			if(title!=null){
				et_title.setText(title);
			}
			if(content!=null){
				et_content.setText(content);
			}
		}
		
		bt_submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String title=et_title.getText().toString();
				String content=et_content.getText().toString();
				if(rowId != null){
					dbAdapter.getDbHelper().updateDiary(rowId, title, content);
					Toast.makeText(DiaryEditActivity.this, "Diary update success!", Toast.LENGTH_SHORT).show();
					
				}else{
					dbAdapter.getDbHelper().createDairy(title, content);
					Toast.makeText(DiaryEditActivity.this, "A diary added!", Toast.LENGTH_SHORT).show();
				}
				Intent intent =new Intent();
				setResult(0, intent);
				finish();
			}
		});
		
	}
	
}
